import * as React from 'react';
import '../styles.less';
import ParagraphCard from '../../../components/ParagraphCard'
import { insertTable } from '../../../utils/WordUtil'
import * as ReactDom from 'react-dom';
import { openDialog } from '../../../utils/WordDialog';
import {
  DetailsList,
  DetailsListLayoutMode,
  Selection,
  SelectionMode,
  IColumn
} from 'office-ui-fabric-react/lib/DetailsList';
import { PrimaryButton } from 'office-ui-fabric-react';

export interface DetailListProps {
  res: any[]
  search?: string
  viewIndex?: any
  isNeedParent?: boolean
}

export interface DetailListStates {

}

export default class DetailList extends React.Component<DetailListProps, DetailListStates> {
  dialog
  constructor(props, context) {
    super(props, context);
  }
  
  render() {
    const { res, isNeedParent = true, search, viewIndex } = this.props
    const { content }: any = res

    const { data } = content

    const items = data
    const currentItem = data[0]
    let columns = Object.keys(currentItem).map((key, index) => {
      const kv = currentItem[key]
      return {
        key: `column${index}`,
        name: key,
        minWidth: 30,
        maxWidth: 100,
        fieldName: key,
        onRender: item => {
          return item[key] instanceof Array ?
            <div>{
              item[key].map((ele, slindex) => <div key={slindex}>{ele}</div>)
            }</div> :
            <span>{item[key]}</span>
        }
      }
    })

    // 加载项只展示部分数据
    // if (isNeedParent && columns.length > 4) {
    //   columns = columns.splice(0, 4)
    // }

    const insert = () => {
      let newData = data.map(dataItem => {
        const element = Object.keys(dataItem).map(key => {
          return dataItem[key] instanceof Array ? dataItem[key].join(',') : dataItem[key].toString()
        })
        return element
      })
      newData.unshift(Object.keys(currentItem))
      console.log(data.length, ', ', columns.length, ', ', newData)
      insertTable(data.length + 1, columns.length, "After", newData)
    }

    const messageCallback = () => {
      insert()
      this.dialog.close();
    }

    const dialogCallback = (asyncResult) => {
      if (asyncResult.status == "failed") {
      }
      else {
        console.info('弹窗打开成功')
        this.dialog = asyncResult.value;
        this.dialog.addEventHandler(Office.EventType.DialogMessageReceived, messageCallback);
      }
    }

    return (
      <div className='detailList'>
        {
          isNeedParent ? (<div onClick={() => openDialog(`/assistantDialog?keyword=${search}&index=${viewIndex}`, dialogCallback)}>
            <ParagraphCard
              title={search}
              menuProps={
                {
                  items: [{
                    key: 'view',
                    text: '预览',
                    iconProps: {
                      iconName: 'View',
                    },
                    onClick: () => {
                      openDialog(`/assistantDialog?keyword=${search}&index=${viewIndex}`, dialogCallback)
                    }
                  }, {
                    key: 'download',
                    text: '插入到word',
                    iconProps: {
                      iconName: 'Download',
                    },
                    onClick: () => insert()
                  }]
                }
              }
            >
              <div style={{ margin: '-15px' }}>
                <DetailsList
                  items={items}
                  compact={true}
                  columns={columns}
                  setKey="set"
                  selectionMode={SelectionMode.none}
                  layoutMode={DetailsListLayoutMode.fixedColumns}
                />
              </div>
            </ParagraphCard>
          </div>) : (
              <React.Fragment>
                <DetailsList
                  items={items}
                  compact={true}
                  columns={columns}
                  setKey="set"
                  selectionMode={SelectionMode.none}
                  layoutMode={DetailsListLayoutMode.fixedColumns}
                />
                <div className="ms-clearfix" style={{ textAlign: 'center', marginTop: '15px' }}>
                  <PrimaryButton className="pull-right" onClick={() => Office.context.ui.messageParent('触发插入事件')}>使用</PrimaryButton>
                </div>
              </React.Fragment>
            )
        }
      </div>
    );
  }

}
